<template>
  <div class="main device-right-container">
    <header class="header-container">
      <div class="title"><span>监控设备列表</span></div>
    </header>
      
      <div class="chart-box">
        <div class="double">
          <div class="row">
            <div v-for="room in roomsCom" :class="{'col-8': room.phaseCount === 1, 'col-16': room.phaseCount === 2 && router === 1, 'col-24': room.phaseCount === 2 && router === 2}" class="mt10 row-padding">
              <state
                :data="room.data"
                @showchart="onShowChart"
                @showWorkedChart="onShowWorkedChart">
              </state>
            </div>
          </div>
        </div>
      </div>

    <!-- 模态窗口 -->
    <!--<electrical-modal :options="chartOptions" :show="true">

    </electrical-modal>-->
    <modal v-if="showChart" @close="showChart = false">
      <div class="chart-content">
        <div class="chart-title">
          <span>{{chartTitle}}</span>
        </div>
        <div class="btn-box">
          <botton-group :btns="chartBtns" :selected="selectedChartBtn" @click="onToggleChartDate"></botton-group>
        </div>
        <Bar width="700px" height="300px" :options="chartOptions"></Bar>
        <div class="close-btn" @click="showChart = false">
          <!--<i class="fa fa-times"></i>-->
        </div>
      </div>
    </modal>
    <modal v-if="showWorkedChart" @close="showWorkedChart = false">
      <div class="chart-content">
        <div class="chart-title">
          <span>{{chartTitle}}</span>
        </div>
        <div class="btn-box">
          <botton-group :btns="chartOnlineBtn" :selected="selectedChartBtn" @click="onToggleOnlineChartDate"></botton-group>     
        </div>
        <Bar width="700px" height="300px" :options="chartDeviceOptions"></Bar>
        <div class="modal-bottom-box">
          <div>
            <span v-show="optionsFlag">在线率:</span>
            <span v-show="!optionsFlag">运行率:</span>
            <span class="modal-bottom-box-online">{{charWorkedStatistics}}</span>
            %</div>
        </div>
        <div class="close-btn" @click="showWorkedChart = false">
          <!--<i class="fa fa-times"></i>-->
        </div>
      </div>
    </modal>
  </div>
</template>

<script>
import State from './State'
import api from 'api'
import formatDate from 'filters/format-date'
import axios from 'axios'
import _ from 'lodash'

export default {
  name: 'DeviceList',

  components: {
    State
  },

  data () {
    return {
      showChart: false,
      router: this.$route.path.split('/')[1] === ':0' ? 1 : 2,
      rowHeight: 100,
      show: false,
      showWorkedChart: false,
      selectedFilter: 0,
      max: 500,
      chartBtns: [
        {
          name: '24小时',
          value: 1
        },
        {
          name: '7天',
          value: 7
        },
        {
          name: '15天',
          value: 15
        }
      ],
      chartOnlineBtn: [
        {
          name: '在线率',
          value: 0
        },
        {
          name: '运行率',
          value: 1
        }
      ],
      chartWorkedBtns: [
        {
          name: '在线率'
        }
      ],
      chartTitle: '',
      selectedChartBtn: {},
      chartDeviceMsg: {},
      psumHistorys: [],
      rooms: [],
      deviceStatus: '',
      optionsFlag: true
    }
  },

  computed: {
    roomsCom () {
      let res = []
      if (!this.rooms || !this.rooms.length) {
        return res
      }
      for (let i = 0; i < this.rooms.length; i++) {
        res.push({
          data: this.rooms[i],
          phaseCount: _.filter(this.rooms[i].devices, (item) => {
            return item.type === 4
          }).length
        })
      }
      return res
    },
    chartOptions () {
      let chartOptions = {
        grid: {
          containLabel: true,
          left: '3%',
          right: '3%',
          bottom: '10%',
          top: '10%'
        },
        legend: {
          align: 'left',
          right: 0,
          top: 0,
          orient: 'horizontal',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: [{
          type: 'category',
          name: '总有功功率正常值范围（ 0 - 470KW）',
          nameLocation: 'middle',
          nameGap: 30,
          boundaryGap: false,
          axisLine: {
            lineStyle: {
              color: '#666666'
            }
          },
          data: this.toChartDate(this.psumHistorys.map(item => item['snapshot_date']))
        }],
        yAxis: [{
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#666666'
            }
          },
          min: 0,
          max: this.yAxisMax()
        }],
        series: [{
          name: '总有功功率（KW）',
          type: 'line',
          stack: '电量',
          data: this.psumHistorys.map(item => item['108'] || 0),
          symbolSize: 6,
          itemStyle: {
            normal: {
              color: '#75a084'
            }
          },
          markLine: {
            data: [[{
              symbol: 'none',
              coord: [0, 0]
            }, {
              symbol: 'none',
              coord: [this.psumHistorys.length - 1, 0],
              name: '最小总有功功率: 0KW',
              label: {
                normal: {
                  show: 'none',
                  formatter: ' '
                }
              }
            }], [{
              symbol: 'none',
              coord: [0, 470]
            }, {
              symbol: 'none',
              coord: [this.psumHistorys.length - 1, 470],
              name: '最大总有功功率: 470KW',
              label: {
                normal: {
                  show: 'none',
                  formatter: ' '
                }
              }
            }]]
          }
        }]
      }
      return chartOptions
    },
    chartWorkOptions () {
      let chartWorkedOptions = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        grid: {
          left: '5%',
          right: '7%',
          bottom: '30%',
          top: '30%',
          containLabel: true
        },
        toolbox: {
        },
        xAxis: [{
          type: 'category',
          data: this.toChartDate(this.sortChart(this.psumHistorys.map(item => item['create_time'] || 0).reverse()))
        }],
        yAxis: [{
          type: 'value',
          min: 0,
          max: 1,
          interval: 1,
          axisLabel: {
            formatter: function (value, index) {
              // 格式化成月/日，只在第一个刻度显示年份
              return value === 1 ? '在线' : '离线'
            }
          }
        }],
        series: [
          {
            name: '状态',
            type: 'line',
            step: 'start',
            markLine: {
              silent: true,
              symbol: 'none',
              data: [
                {
                  yAxis: this.deviceStatus
                }
              ]
            },
            itemStyle: {
              normal: {
                color: '#29aaaa'
              }
            },
            data: this.sortChart(this.psumHistorys.map(item => item['status'] || 0)).reverse()
          }
        ]
      }
      return chartWorkedOptions
    },
    // IO设备运行率options
    chartIoOptions () {
      let chartIoOptions = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        grid: {
          left: '5%',
          right: '7%',
          bottom: '30%',
          top: '30%',
          containLabel: true
        },
        toolbox: {
        },
        xAxis: [{
          type: 'category',
          data: this.toChartDate(this.psumHistorys.map(item => item['snapshot_date'] || 0))
        }],
        yAxis: [{
          type: 'value',
          min: 0,
          max: 1,
          interval: 1,
          axisLabel: {
            formatter: function (value, index) {
              // 格式化成月/日，只在第一个刻度显示年份
              return value === 1 ? '运行' : '离线'
            }
          }
        }],
        series: [
          {
            name: '状态',
            type: 'line',
            step: 'start',
            markLine: {
              silent: true,
              symbol: 'none',
              data: [
                {
                  yAxis: this.deviceStatus
                }
              ]
            },
            itemStyle: {
              normal: {
                color: '#29aaaa'
              }
            },
            data: this.psumHistorys.map(item => item['4'] || 0)
          }
        ]
      }
      return chartIoOptions
    },
    // 判断使用哪一个options,针对于
    chartDeviceOptions () {
      return this.optionsFlag ? this.chartWorkOptions : this.chartIoOptions
    },
    // 对在线率进行统计
    charWorkedStatistics () {
      let onlineNumber = 0
      let arr = []
      if (this.optionsFlag) {
        arr = this.psumHistorys.map(item => item['status'] || 0)
      } else {
        arr = this.psumHistorys.map(item => item['4'] || 0)
      }
      arr.forEach(item => {
        if (item === 1) {
          onlineNumber++
        }
      })
      if (arr.length === 0) {
        return 0
      } else {
        return parseInt(onlineNumber / arr.length * 100)
      }
    }
  },

  mounted () {
    this.$nextTick(() => {
      this.rowHeight = 70
      this.show = true
    })
    this.initChart()
    this.getRooms()
    this.requestRestfulData()
  },

  methods: {
    getRooms () {
      axios.get('static/data/devices/electric.json').then((res) => {
        switch (this.$route.path.split('/')[1]) {
          case ':0':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
          case ':1':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '香槟'
            })
            break
          case ':2':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
          case ':3':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
        }
      }).catch((err) => {
        this.handleError(err)
      })
    },

    initChart () {
      this.selectedChartBtn = this.chartOnlineBtn[0]
    },

    getChartData () {
      let { productId, deviceId } = this.chartDeviceMsg
      let day = this.selectedChartBtn.value || 1
      let params = {
        'offset': 0,
        'limit': 2500,
        'date': {
          'begin': new Date() - day * 1000 * 60 * 60 * 24,
          'end': +new Date()
        },
        'rule_id': '58d09973c5740e446cc94699'
      }
      api.snapshot.getSnapshot(productId, deviceId, params).then((res) => {
        this.psumHistorys = res.data.list
      }).catch((res) => {
        this.handleError(res)
      })
    },
    // 获取I/O设备历史运行率
    getIOchartData () {
      let { ioProductId, deviceId } = this.chartDeviceMsg
      let params = {
        'offset': 0,
        'limit': 2500,
        'date': {
          'begin': new Date() - 1000 * 60 * 60 * 24,
          'end': +new Date()
        },
        'rule_id': '58d1e30bc5740e43eff684d9'
      }
      api.snapshot.getSnapshot(ioProductId, deviceId, params).then((res) => {
        this.psumHistorys = res.data.list
      }).catch((res) => {
        this.handleError(res)
      })
    },
    // 获得设备历史在线数据
    getChartWorkedData () {
      let { productId, deviceId } = this.chartDeviceMsg
      let params = {
        'offset': 0,
        'limit': 24,
        'query': {
          'device_id': deviceId,
          'product_id': productId
        }
      }
      api.device.getRecords(params).then((res) => {
        this.psumHistorys = res.data.list
      }).catch((res) => {
        this.handleError(res)
      })
    },

    onResize () {
    },

    onShowChart (deviceMsg, chartTitle) {
      this.initChart()
      this.chartDeviceMsg = deviceMsg
      this.chartTitle = chartTitle
      this.getChartData()
      // this.chartOptions = chartOptions
      this.showChart = true
    },
    onShowWorkedChart (deviceMsg, deviceStatus) {
      this.initChart()
      this.chartDeviceMsg = deviceMsg
      this.deviceStatus = deviceMsg.chartDeviceMsg
      // 每次点击进来都需要进行一次重置
      this.optionsFlag = true
      this.chartTitle = this.optionsFlag ? '近期设备在线概况' : '24小时设备运行概况'
      this.getChartWorkedData()
      // this.chartOptions = chartOptions
      this.showWorkedChart = true
    },
    // 在线与运行表格的切换
    onToggleOnlineChart (chartFlag) {
      // 切换到哪种类型的表格
      this.optionsFlag = chartFlag
      this.chartTitle = this.optionsFlag ? '近期设备在线概况' : '24小时设备运行概况'
      // 申请哪一个接口的数据
      return chartFlag ? this.getChartWorkedData() : this.getIOchartData()
    },

    onToggleChartDate (btn) {
      this.selectedChartBtn = btn
      // 解决切换数据的时候，闪过混乱曲线图，但是会出现空屏的现象
      this.psumHistorys = []
      this.getChartData()
    },

    onToggleOnlineChartDate (btn) {
      this.selectedChartBtn = btn
      let chartFlag = null
      btn.value === 0 ? chartFlag = true : chartFlag = false
      // 解决切换数据的时候，闪过混乱曲线图，但是会出现空屏的现象
      this.psumHistorys = []
      this.onToggleOnlineChart(chartFlag)
    },

    toChartDate (dateArr) {
      let result = []
      dateArr.forEach((date) => {
        let resultDate
        if (this.selectedChartBtn.value === 1) {
          resultDate = formatDate(date, 'hh:mm:ss')
        } else {
          resultDate = formatDate(date, 'MM-dd')
        }
        result.push(resultDate)
      })
      return result
    },
    // 对返回来的时间做排序
    sortChart (data) {
      return _.sortBy(data, function (item) { return item['create_time'] || 0 })
    },

    yAxisMax () {
      let arr = this.psumHistorys.map(item => item['108'] || 0)
      let max = Math.max(...arr)
      const range = 500
      this.max = max > range ? max : range
      return Math.ceil(this.max)
    },
    requestRestfulData () {
      this.$store.dispatch('updateElectricalDeviceStatusData')
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../../../assets/stylus/base'

.device-right-container {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  font-size: 12px;
  
  .title {
    margin-left 10px
    height 50px
    line-height 50px
    font-size 14px
  }

  .chart-box {
    width: 100%;
    position:absolute;
    top:50px;
    bottom:0px;
    over-flow:hidden;
    .double{
      width:100%;
      height: 100%;
      padding-right:50%;
      overflow: auto;
    }
  }

  .triangle {
    triangle(#fff, 10px);
    margin-left: 5px;
  }
}

.row-padding {
  padding: 0 0 0 10px;
  box-sizing: border-box;
}

.chart-content
  position relative
  width 100%
  height 100%
  background #1e1e1e
  padding 20px
  box-sizing border-box
  color #ccc

  .chart-title
    width 100%
    height 30px
    line-height 30px
    font-size 15px
  .btn-box
    position relative
    z-index 1000
    text-align center
  .modal-bottom-box {
    position absolute
    bottom 30px
    width 100%
    text-align center
    color #ccc
    .modal-bottom-box-online {
      font-size 14px
    }
  }
  .close-btn
    background:url('../../../../assets/images/u508.png') no-repeat center center
    width 30px
    height 30px
    position absolute
    right 10px
    top 10px
    font-size 25px
    cursor pointer

</style>
